package receiver;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.gson.Gson;
import com.wq.cycling.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

import activity.MainActivity;
import bean.EntityForPush;
import cn.jpush.android.api.JPushInterface;

/**
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class JPushReceiver extends BroadcastReceiver {
	private Context mContext;
	private static final String TAG = "JPush";

	@Override
	public void onReceive(Context context, Intent intent) {
		this.mContext = context;
		Bundle bundle = intent.getExtras();
		Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
			// send the Registration Id to your server...

		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)
					+ bundle.getString(JPushInterface.EXTRA_TITLE));
			/*getNotification(bundle.getString(JPushInterface.EXTRA_TITLE),
					bundle.getString(JPushInterface.EXTRA_MESSAGE), bundle.getString(JPushInterface.EXTRA_EXTRA));*/

			showNotification(bundle.getString(JPushInterface.EXTRA_TITLE),
					bundle.getString(JPushInterface.EXTRA_MESSAGE),mContext,0);

		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
			int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的I: " + notifactionId);
			try {
				//解析透传过来的json
				Gson gson = new Gson();
				EntityForPush pushEntity = gson.fromJson(bundle.getString(JPushInterface.EXTRA_EXTRA), EntityForPush.class);
				pushEntity = gson.fromJson(pushEntity.getContent(), EntityForPush.class);
				if (pushEntity != null) {
					showNotification(pushEntity.getTitle().isEmpty() ? context.getResources().getString(R.string.push_title) : pushEntity.getTitle(), pushEntity.getContent(), mContext, 0);
					sendBroadcast(1, pushEntity.getContent(), pushEntity.getTitle().isEmpty() ? context.getResources().getString(R.string.push_title) : pushEntity.getTitle());
				}
			}catch (Exception e){

			}
				// TODO Auto-generated catch block
		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
		} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
		} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
			boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
			Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
		} else {
			Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
		}
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
				if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
					Log.i(TAG, "This message has no Extra data");
					continue;
				}

				try {
					JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
					Iterator<String> it = json.keys();

					while (it.hasNext()) {
						String myKey = it.next().toString();
						sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]");
					}
				} catch (JSONException e) {
					Log.e(TAG, "Get message extra JSON error!");
				}

			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}

	/**
	 * 程序是否运行在后台
	 *
	 * @param context
	 * @return
	 */
	public static boolean isApplicationBroughtToBackground(final Context context) {
		try {
			ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningTaskInfo> tasks = am.getRunningTasks(1);
			if (!tasks.isEmpty()) {
				ComponentName topActivity = tasks.get(0).topActivity;
				if (!topActivity.getPackageName().equals(context.getPackageName())) {
					return true;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public static boolean isBackground(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		for (RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(context.getPackageName())) {
				Log.i(context.getPackageName(), "此appimportace ="
						+ appProcess.importance
						+ ",context.getClass().getName()="
						+ context.getClass().getName());
				if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
					Log.i(context.getPackageName(), "处于后台"
							+ appProcess.processName);
					return true;
				} else {
					Log.i(context.getPackageName(), "处于前台"
							+ appProcess.processName);
					return false;
				}
			}
		}
		return false;
	}

	private void showNotification(String title, String content,Context context, int type) {
		int notifytype = R.mipmap.icon_small_ic_launcher;
		String mtitle = title;
		String mcontent = content;
		Bitmap btm = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);// 图标
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
				.setSmallIcon(notifytype).setContentTitle(mtitle)// 标题
				.setContentText(mcontent)// 内容
				.setVibrate(new long[] { 100, 400, 100, 400 })// 震动
				.setLights(0xff0000ff, 300, 0)// 提示灯
				.setDefaults(Notification.DEFAULT_SOUND);
		//.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" +R.raw.msg))
		//.setPriority(Notification.PRIORITY_MAX);// 设置优先级;
		mBuilder.setTicker("有新消息");// 第一次提示消息的时候显示在通知栏上
		// mBuilder.setNumber(12);
		mBuilder.setLargeIcon(btm);
		mBuilder.setAutoCancel(true);// 自己维护通知的消失
		// 构建一个Intent
		Intent resultIntent;
		resultIntent = new Intent(context, MainActivity.class);
		PendingIntent resultPendingIntent;

		// 封装一个Intent
		resultPendingIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
		// 设置通知主题的意图
		mBuilder.setContentIntent(resultPendingIntent);
		// 获取通知管理器对象
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.notify(0, mBuilder.build());
	}

	private void getNotification(String mTitle, String mContent,String mCustomContent) {
		String title = mTitle;
		String content = mContent;
		String customContent = mCustomContent;
		KeyguardManager mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
		boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
		if (isApplicationBroughtToBackground(mContext)||isBackground(mContext)||flag) {
			//后台
			showNotification(title, content,mContext, 999);
		} else {
			//前台
			sendBroadcast(3, content, title);
		}
	}
	/**
	 * 启动弹窗
	 * @param code 弹窗编号
	 * @param content 弹窗内容
	 * @param title 弹窗标题
	 */
	public void sendBroadcast(int code,String content,String title){
		Intent in = new Intent("io.zhixun");
		in.putExtra("PushId", code);
		in.putExtra("Title", title);
		in.putExtra("Content", content);
		mContext.getApplicationContext().sendBroadcast(in);
	}

}
